#include "DirAnimation.hpp"

namespace sl
{
	DirAnimation::DirAnimation() : Animation(), Direction()
	{}

	DirAnimation::DirAnimation(const Animation& anim) : Animation(anim), Direction()
	{}

	DirAnimation* DirAnimation::AddFrame(const FrameInfo& info)
	{
		myFrameInfos[myDirection].push_back(info);
		return this;
	}

	DirAnimation* DirAnimation::AddFrame(Direction::Dir dir, const FrameInfo& info)
	{
		myFrameInfos[dir].push_back(info);
		return this;
	}

	DirAnimation* DirAnimation::AddFrame(unsigned int frame, unsigned int delay, const sf::Vector2i& offset)
	{
		return AddFrame(FrameInfo(frame, delay, offset));
	}

	DirAnimation* DirAnimation::AddFrame(Direction::Dir dir, unsigned int frame, unsigned int delay, const sf::Vector2i& offset)
	{
		return AddFrame(dir, FrameInfo(frame, delay, offset));
	}

	DirAnimation* DirAnimation::SetSize(const sf::Vector2i& size)
	{
		mySize = size;
		return this;
	}

	sf::IntRect DirAnimation::GetFrame()
	{
		return Animation::GetFrame(myFrameInfos[myDirection][myCurFrame]);
	}

	DirAnimation* DirAnimation::Start()
	{
		myIsRunning = true;
		if (myFrameInfos[myDirection].size() > 0)
		{
			SetSubRect(Animation::GetFrame(myFrameInfos[myDirection][myCurFrame]));
			SetOffset(myFrameInfos[myDirection][myCurFrame]);
		}
		return this;
	}

	DirAnimation* DirAnimation::Stop()
	{
		myIsRunning = false;
		if (myFrameInfos[myDirection].size() > 0)
			SetSubRect(sf::IntRect(0, 0, GetTexture()->GetWidth(), GetTexture()->GetHeight()));
		return this;
	}

	DirAnimation* DirAnimation::Pause()
	{
		myIsRunning = !myIsRunning;
		return this;
	}

	DirAnimation* DirAnimation::Restart()
	{
		Stop();
		return Start();
	}

	DirAnimation* DirAnimation::Update(float time)
	{
		if (myIsRunning)
		{
			unsigned int tick = time * myTicks;
			if (myFrameInfos[myDirection].size() > 0 && tick >= 1)
			{
				tick += myTick;
				while (tick >= myFrameInfos[myDirection][myCurFrame].GetDelay())
				{
					tick -= myFrameInfos[myDirection][myCurFrame].GetDelay();
					myCurFrame++;
					if (myCurFrame >= myFrameInfos[myDirection].size())
						myCurFrame = 0;
				}

				myTick = tick;

				SetSubRect(Animation::GetFrame(myFrameInfos[myDirection][myCurFrame]));
				SetOffset(myFrameInfos[myDirection][myCurFrame]);
			}
		}
		return this;
	}

	DirAnimation* DirAnimation::SetDirection(Direction::Dir dir)
	{
		if (dir != myDirection)
		{
			if (myIsRunning)
				Stop();
			Direction::SetDirection(dir);
			Start();
		}

		return this;
	}
}